package com.cskaoyan.mall.product.service.impl;

import com.cskaoyan.mall.product.config.MyMinioConfig;
import com.cskaoyan.mall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {
    @Autowired
    MyMinioConfig minioConfig;
    @Autowired
    MinioClient minioClient;
    @Override
    public String uploadPic(MultipartFile myfile) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //在这里执行文件上传的操作

        //创建对象名称
        String objectName= UUID.randomUUID().toString().replaceAll("-","");

        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioConfig.getBucketName())
                        .contentType(myfile.getContentType())
                        .stream(myfile.getInputStream(), myfile.getSize(), -1)
                        .object(objectName)
                        .build()
        );
        //然后要获取图片的url
        String url=minioConfig.getEndpointUrl()+"/"+minioConfig.getBucketName()+"/"+objectName;

        return url;
    }
}
